//
//  CityShortNameViewController.m
//  huisaoche
//
//  Created by Steven.Yung on 2017/8/7.
//  Copyright © 2017年 Minidai. All rights reserved.
//

#import "CityShortNameViewController.h"
#import "ShortCityNameModel.h"

@interface CityShortNameViewController () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate>

@property(nonatomic, strong) UICollectionView *collectionView;

@property(nonatomic, copy) SelectedCityBlock _Nonnull selectedCityBlock;

@property(nonatomic, strong) NSArray *cities;

@end

@implementation CityShortNameViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    tapGesture.delegate = self;
    [self.view addGestureRecognizer:tapGesture];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    CGRect frame = self.collectionView.frame;
    frame.origin.y = kScreenHeight - frame.size.height;
    [UIView animateWithDuration:0.25 animations:^{
        [self.collectionView setFrame:frame];
    }];
}

+ (void)showShortCityPicker:(UIViewController *)viewController cityNameArray:(NSArray *)cities selectedCityHandler:(SelectedCityBlock)handler {
    
    CityShortNameViewController *picker = [UIStoryboard viewControllerWithIdentifier:[CityShortNameViewController description]];
    picker.cities = [cities copy];
    [picker setupUI];
    picker.selectedCityBlock = handler;
    
    [viewController.view addSubview:picker.view];
    [viewController addChildViewController:picker];
}

- (void)setupUI {
    
    [self.collectionView reloadData];

}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat itemWidth = (kScreenWidth - 5 * 1) / 6;  //6列，间隔是1
        layout.itemSize = CGSizeMake(itemWidth, itemWidth);
        layout.minimumLineSpacing = 1.0;
        layout.minimumInteritemSpacing = 1.0;
        
        NSInteger rows = (self.cities.count - 1) / 6 + 1;  //计算行数
        CGFloat collectionViewHeight = itemWidth * rows + (rows - 1);  //计算CollectionView应有的高度
        CGRect frame = CGRectMake(0, kScreenHeight, kScreenWidth, collectionViewHeight);
        _collectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:layout];
        [_collectionView registerClass:[CityShortNameCell class] forCellWithReuseIdentifier:@"cell"];
        _collectionView.backgroundColor = kColorBackground;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        [self.view addSubview:_collectionView];
    }
    
    return _collectionView;
}
//解决点击View的手势与UICollectionView点击手势冲突
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {

    if (touch.view != self.view) {
        return NO;
    }
    return YES;
}

#pragma mark - UICollectionView Datasource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.cities.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CityShortNameCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    ProCityModel *model = self.cities[indexPath.item];
    cell.nameLabel.text = model.abbr;
    
    return cell;
}

#pragma mark - UICollectionView Delegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    if (self.selectedCityBlock) {
        self.selectedCityBlock(indexPath.item);
    }
    [self dismissPicker];
}

- (void)tapAction:(UITapGestureRecognizer *)tapGesture {
    [self dismissPicker];
}

- (void)dismissPicker {
    
    CGRect frame = self.collectionView.frame;
    frame.origin.y = kScreenHeight;
    [UIView animateWithDuration:0.25
                     animations:^{
                         
                         [self.collectionView setFrame:frame];
                         self.view.alpha = 0.0;
                     }
                     completion:^(BOOL finished) {
                         [self didMoveToParentViewController:nil];
                         [self.view removeFromSuperview];
                         [self removeFromParentViewController];
                     }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

@implementation CityShortNameCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    
    if (self) {
        [self initialContents];
    }
    return self;
}

- (instancetype)init {
    self = [super init];
    
    if (self) {
        [self initialContents];
    }
    
    return self;
}

- (void)initialContents {
    self.nameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    self.nameLabel.textColor = kColorBlack;
    self.nameLabel.font = [UIFont systemFontOfSize:14.0];
    
    [self.contentView addSubview:self.nameLabel];
    self.contentView.backgroundColor = [UIColor whiteColor];
    
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.contentView);
        make.centerY.equalTo(self.contentView);
    }];
}

@end



